package com.concurrent.sample.business.trade.service.impl;

import com.concurrent.sample.business.event.param.trade.TradeExecReportDTO;
import com.concurrent.sample.business.trade.entity.TradeOrderEntity;
import com.concurrent.sample.business.trade.repo.TradeOrderRepo;
import com.concurrent.sample.business.trade.service.TradeOrderService;
import com.concurrent.sample.common.util.LongUtil;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Slf4j
public class TradeOrderServiceImpl implements TradeOrderService {

  private final TradeOrderRepo orderRepo;

  @Transactional(rollbackFor = Exception.class)
  @Override
  public void save(List<TradeOrderEntity> orderEntities) {
    orderRepo.saveAll(orderEntities);
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public TradeOrderEntity updateByExecutionReport(TradeExecReportDTO execReport) {
    TradeOrderEntity orderEntity = getById(execReport.getOriginalOrderId());

    // 更新订单状态、数量
    orderEntity.setOrderStatus(execReport.getOrderStatus())
        .setLeaveQty(LongUtil.minusByNullToZero(orderEntity.getLeaveQty(), execReport.getQuantity()))
        .setExecPrice(execReport.getExecPrice())
        .setMemo(execReport.getMemo())
    ;

    return orderEntity;
  }

  @Override
  public TradeOrderEntity getById(Long id) {
    return orderRepo.findById(id).orElse(null);
  }

  @Override
  public List<TradeOrderEntity> getByIds(List<Long> ids) {
    return orderRepo.findAllById(ids);
  }

  @Override
  public TradeOrderEntity getByEventId(Long eventId) {
    return orderRepo.findByEventId(eventId);
  }

}
